const { NodeSSH } = require("node-ssh");

class AutoUploadPlugin {
  constructor(options) {
    this.ssh = new NodeSSH();
    this.options = options;
    this.connectionStates = true;
  }

  apply(compiler) {
    compiler.hooks.afterEmit.tapAsync(
      "AutoUploadPlugin",
      async (compilation, callback) => {
        // 1.获取输出文件夹
        const outputPath = compilation.outputOptions.path;

        // 2.连接服务器(ssh连接)
        await this.connectServer();

        if (this.connectionStates) {
          // 3.删除原目录中的内容
          const serverDir = this.options.remotePath;
          await this.ssh.execCommand(`rm -rf ${serverDir}/*`);

          // 4.上传文件到服务器(ssh)
          await this.uploadFile(outputPath, serverDir);

          // 5.关闭ssh
          this.ssh.dispose();
        }

        callback();
      }
    );
  }

  async connectServer() {
    try {
      await this.ssh.connect({
        host: this.options.host,
        username: this.options.username,
        password: this.options.password,
      });
    } catch {
      this.connectionStates = false;
      console.log("AutoUploadPlugin: connection failed");
    }

    this.connectionStates && console.log("connection success");
  }

  async uploadFile(localPath, remotePath) {
    const status = await this.ssh.putDirectory(localPath, remotePath, {
      recursive: true,
      concurrency: 10,
    });

    console.log("upload", status ? "success" : "failed");
  }
}

module.exports = AutoUploadPlugin;
